'use client'

import React, { useState } from 'react';
import Image from 'next/image';
import { UserIcon, ArrowUpTrayIcon } from '@heroicons/react/24/outline';
import DialogWrapper from './dialog-wrapper';
import { UserProfile } from '@/types/user';
import { userApi } from '@/lib/api';

interface ProfileDialogProps {
  isOpen: boolean;
  onClose: () => void;
  profile: UserProfile | null;
  onSave: (updatedProfile: UserProfile) => Promise<void>;
}

export default function ProfileDialog({
  isOpen,
  onClose,
  profile,
  onSave
}: ProfileDialogProps) {
  const [editedProfile, setEditedProfile] = useState<UserProfile | null>(profile);
  const [isSaving, setIsSaving] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const fileInputRef = React.useRef<HTMLInputElement>(null);

  // 当profile变化时更新编辑状态
  React.useEffect(() => {
    setEditedProfile(profile);
    setAvatarPreview(null);
    setAvatarFile(null);
    setSuccessMessage(null);
    setErrorMessage(null);
  }, [profile]);

  if (!profile) return null;

  // 处理文件选择
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 验证文件类型和大小
    if (!file.type.startsWith('image/')) {
      setErrorMessage('请选择图片文件');
      return;
    }

    if (file.size > 5 * 1024 * 1024) { // 5MB
      setErrorMessage('图片大小不能超过5MB');
      return;
    }

    // 创建预览URL
    const objectUrl = URL.createObjectURL(file);
    setAvatarPreview(objectUrl);
    setAvatarFile(file);
    setErrorMessage(null);

    return () => URL.revokeObjectURL(objectUrl);
  };

  // 触发文件选择框
  const handleUploadClick = () => {
    fileInputRef.current?.click();
  };

  // 上传头像
  const uploadAvatar = async (file: File): Promise<string> => {
    setIsUploading(true);
    try {
      const result = await userApi.uploadAvatar(file);
      return result.imageUrl;
    } catch (error) {
      console.error('上传头像失败:', error);
      throw new Error('上传头像失败');
    } finally {
      setIsUploading(false);
    }
  };

  // 保存个人资料
  const handleSave = async () => {
    if (!editedProfile) return;
    
    setIsSaving(true);
    setSuccessMessage(null);
    setErrorMessage(null);
    
    try {
      // 如果有新的头像文件，先上传
      let updatedProfile = { ...editedProfile };
      
      if (avatarFile) {
        try {
          const imageUrl = await uploadAvatar(avatarFile);
          updatedProfile.image = imageUrl;
        } catch (error) {
          setErrorMessage('上传头像失败，请稍后重试');
          setIsSaving(false);
          return;
        }
      }
      
      // 保存更新后的个人资料
      await onSave(updatedProfile);
      setSuccessMessage('个人资料已更新');
      
      // 成功后关闭对话框
      setTimeout(() => {
        onClose();
      }, 1500);
    } catch (error) {
      console.error('更新个人资料失败:', error);
      setErrorMessage('更新失败，请稍后重试');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <DialogWrapper 
      isOpen={isOpen} 
      onClose={onClose}
      title="个人资料"
      size="md"
    >
      {successMessage && (
        <div className="mb-4 p-3 bg-green-50 border-l-4 border-green-500 text-green-700 rounded-md">
          <p>{successMessage}</p>
        </div>
      )}
      
      {errorMessage && (
        <div className="mb-4 p-3 bg-red-50 border-l-4 border-red-500 text-red-700 rounded-md">
          <p>{errorMessage}</p>
        </div>
      )}
      
      <div className="space-y-4">
        {/* 头像上传 */}
        <div className="flex items-center justify-center mb-6">
          <div className="relative h-24 w-24 rounded-full overflow-hidden bg-gray-100">
            {(avatarPreview || editedProfile?.image) ? (
              <Image
                src={avatarPreview || editedProfile?.image || ''}
                alt="用户头像"
                fill
                className="object-cover"
              />
            ) : (
              <div className="h-full w-full flex items-center justify-center">
                <UserIcon className="h-12 w-12 text-gray-400" />
              </div>
            )}
            
            {isUploading && (
              <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center">
                <div className="animate-spin h-8 w-8 border-4 border-white border-t-transparent rounded-full"></div>
              </div>
            )}
          </div>
          <div className="ml-5">
            <input
              ref={fileInputRef}
              type="file"
              className="hidden"
              accept="image/*"
              onChange={handleFileChange}
              aria-label="上传头像"
            />
            <button
              type="button"
              onClick={handleUploadClick}
              className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
              disabled={isUploading}
            >
              <ArrowUpTrayIcon className="h-4 w-4 mr-2" />
              上传新头像
            </button>
            <p className="mt-1 text-xs text-gray-500">JPG, PNG 或 GIF, 最大 5MB</p>
          </div>
        </div>
        
        {/* 个人资料表单 */}
        <div>
          <label htmlFor="profile-name" className="block text-sm font-medium text-gray-700">名称</label>
          <input
            type="text"
            id="profile-name"
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
            value={editedProfile?.name || ''}
            onChange={(e) => setEditedProfile(prev => prev ? {...prev, name: e.target.value} : null)}
          />
        </div>
        
        <div>
          <label htmlFor="profile-email" className="block text-sm font-medium text-gray-700">电子邮箱</label>
          <input
            type="email"
            id="profile-email"
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm bg-gray-50 sm:text-sm"
            value={editedProfile?.email || ''}
            readOnly
          />
          <p className="mt-1 text-xs text-gray-500">电子邮箱不可更改</p>
        </div>
        
        <div>
          <label htmlFor="profile-bio" className="block text-sm font-medium text-gray-700">个人简介</label>
          <textarea
            id="profile-bio"
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
            rows={3}
            value={editedProfile?.bio || ''}
            onChange={(e) => setEditedProfile(prev => prev ? {...prev, bio: e.target.value} : null)}
          />
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label htmlFor="profile-job" className="block text-sm font-medium text-gray-700">职位</label>
            <input
              type="text"
              id="profile-job"
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
              value={editedProfile?.jobTitle || ''}
              onChange={(e) => setEditedProfile(prev => prev ? {...prev, jobTitle: e.target.value} : null)}
            />
          </div>
          <div>
            <label htmlFor="profile-location" className="block text-sm font-medium text-gray-700">位置</label>
            <input
              type="text"
              id="profile-location"
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
              value={editedProfile?.location || ''}
              onChange={(e) => setEditedProfile(prev => prev ? {...prev, location: e.target.value} : null)}
            />
          </div>
        </div>
      </div>
      
      {/* 操作按钮 */}
      <div className="mt-6 flex justify-end space-x-3">
        <button
          type="button"
          className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
          onClick={onClose}
          disabled={isSaving || isUploading}
        >
          取消
        </button>
        <button
          type="button"
          className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none disabled:opacity-50"
          onClick={handleSave}
          disabled={isSaving || isUploading}
        >
          {isSaving || isUploading ? '保存中...' : '保存'}
        </button>
      </div>
    </DialogWrapper>
  );
} 